<script setup lang="ts">
import { getUserInfoAPI, updateUserInfoAPI } from '@/services/profile'
import type { UserInfoResponse } from '@/types/profile'
import { onLoad } from '@dcloudio/uni-app'
import { ref } from 'vue'
import { uploadProfileAvatarAPI } from '../../services/profile'
import { useMemberStore } from '@/stores'

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()
// 用户信息
const userInfo = ref<UserInfoResponse>({} as UserInfoResponse)
// 获取用户仓库
const memberStore = useMemberStore()
// 省市区编码(不涉及页面数据展示，无需使用响应式定义)
let reginCode: string[] = []

// 获取用户信息
const getUserInfo = async () => {
  const result = await getUserInfoAPI()
  // 存储用户信息
  userInfo.value = result.result
}
// 更换头像的回调(小程序端)
const onChooseAvatar: UniHelper.ButtonOnChooseavatar = async (event) => {
  // 调用上传文件的接口方法
  const result: any = await uploadProfileAvatarAPI(event.detail.avatarUrl)
  if (result.code === 200) {
    // 更新当前页面头像
    userInfo.value!.avatar = result.data
    // 更新仓库中用户头像
    memberStore.profile!.avatar = result.data
    // 提示用户更新成功
    uni.showToast({
      title: '更新头像成功',
      icon: 'success',
    })
  } else {
    uni.showToast({
      title: '更新头像失败',
      icon: 'error',
    })
  }
}
// 更新头像的回调(H5端 APP端)
const chooseAvatarOther = () => {
  // #ifndef MP-WEIXIN
  uni.chooseImage({
    count: 1,
    success: async ({ tempFilePaths }) => {
      console.log(tempFilePaths)
      // 调用上传文件的接口方法
      const result: any = await uploadProfileAvatarAPI(tempFilePaths[0])
      console.log(result)
      if (result.code === 200) {
        // 更新当前页面头像
        userInfo.value!.avatar = result.data
        // 更新仓库中用户头像
        memberStore.profile!.avatar = result.data
        // 提示用户更新成功
        uni.showToast({
          title: '更新头像成功',
          icon: 'success',
        })
      } else {
        uni.showToast({
          title: '更新头像失败',
          icon: 'error',
        })
      }
    },
  })
  // #endif
}
// 更改性别的回调
const onGenderChange: UniHelper.RadioGroupOnChange = (event) => {
  // 修改用户信息
  userInfo.value.gender = event.detail.value as '男' | '女'
}
// 选择日期的回调
const onSelectData: UniHelper.DatePickerOnChange = (event) => {
  // 存储用户选择的出生日期
  userInfo.value.birthday = event.detail.value
}
// 更改地址的回调
const onSelectRegion: UniHelper.RegionPickerOnChange = (event) => {
  // 存储用户选择的省市区，用于页面展示
  userInfo.value.fullLocation = event.detail.value.join(' ')
  // 存储省市区编码，用于更新数据
  reginCode = event.detail.code as string[]
}
// 保存用户信息
const onSave = async () => {
  // 获取参数
  const { nickname, profession, gender, birthday } = userInfo.value
  // 发请求更新用户信息，会返回最新的用数据
  const result = await updateUserInfoAPI({
    nickname,
    profession,
    gender,
    birthday,
    provinceCode: reginCode[0],
    cityCode: reginCode[1],
    countyCode: reginCode[2],
  })
  // 更新当前页面用户信息
  userInfo.value = result.result
  // 修改用户仓库中的用户数据
  memberStore.profile!.nickname = result.result.nickname as string
  // 提示成功
  await uni.showToast({
    title: '修改成功',
    icon: 'success',
  })
  // 成功提示延迟0.5s后返回上一级页面
  setTimeout(() => {
    // 返回上一级页面
    uni.navigateBack()
  }, 500)
}

onLoad(() => {
  // 获取用户信息
  getUserInfo()
})
</script>

<template>
  <view class="viewport">
    <!-- 导航栏 -->
    <view class="navbar" :style="{ paddingTop: safeAreaInsets?.top + 'px' }">
      <navigator
        open-type="navigateBack"
        class="back icon-left"
        hover-class="none"
      ></navigator>
      <view class="title">个人信息</view>
    </view>
    <!-- 头像 -->
    <view class="avatar">
      <button
        class="avatar-button"
        open-type="chooseAvatar"
        @chooseavatar="onChooseAvatar"
        @tap="chooseAvatarOther"
      >
        <image class="image" :src="userInfo.avatar" />
      </button>
      <text class="text">点击修改头像</text>
    </view>
    <!-- 表单 -->
    <view class="form">
      <!-- 表单内容 -->
      <view class="form-content">
        <view class="form-item">
          <text class="label">账号</text>
          <text class="account">{{ userInfo.account }}</text>
        </view>
        <view class="form-item">
          <text class="label">昵称</text>
          <input
            class="input"
            type="nickname"
            placeholder="请填写昵称"
            v-model="userInfo.nickname"
          />
        </view>
        <view class="form-item">
          <text class="label">性别</text>
          <radio-group @change="onGenderChange">
            <label class="radio">
              <radio
                value="男"
                color="#27ba9b"
                :checked="userInfo.gender === '男'"
                style="transform: scale(0.7)"
              />
              男
            </label>
            <label class="radio">
              <radio
                value="女"
                color="#27ba9b"
                :checked="userInfo.gender === '女'"
                style="transform: scale(0.7)"
              />
              女
            </label>
          </radio-group>
        </view>
        <view class="form-item">
          <text class="label">出生日期</text>
          <picker
            class="picker"
            mode="date"
            start="1900-01-01"
            :end="new Date()"
            :value="userInfo.birthday"
            @change="onSelectData"
          >
            <view v-if="userInfo.birthday">{{ userInfo.birthday }}</view>
            <view class="placeholder" v-else>请选择日期</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">城市</text>
          <picker
            class="picker"
            mode="region"
            :value="userInfo.fullLocation?.split(' ')"
            @change="onSelectRegion"
          >
            <view v-if="userInfo.fullLocation">{{ userInfo.fullLocation }}</view>
            <view class="placeholder" v-else>请选择城市</view>
          </picker>
        </view>
        <view class="form-item">
          <text class="label">职业</text>
          <input
            class="input"
            type="text"
            placeholder="请填写职业"
            v-model="userInfo.profession"
          />
        </view>
      </view>
      <!-- 提交按钮 -->
      <button class="form-button" @tap="onSave">保 存</button>
    </view>
  </view>
</template>

<style lang="scss">
page {
  background-color: #f4f4f4;
}

.viewport {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-image: url(https://pcapi-xiaotuxian-front-devtest.itheima.net/miniapp/images/order_bg.png);
  background-size: auto 420rpx;
  background-repeat: no-repeat;
}

// 导航栏
.navbar {
  position: relative;

  .title {
    height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 16px;
    font-weight: 500;
    color: #fff;
  }

  .back {
    position: absolute;
    height: 40px;
    width: 40px;
    left: 0;
    font-size: 20px;
    color: #fff;
    display: flex;
    justify-content: center;
    align-items: center;
  }
}

// 头像
.avatar {
  text-align: center;
  width: 100%;
  height: 260rpx;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  .avatar-button {
    background-color: transparent;
    &::after {
      border: none;
    }
    image {
      width: 160rpx;
      height: 160rpx;
      border-radius: 50%;
    }
  }

  .text {
    display: block;
    padding-top: 20rpx;
    line-height: 1;
    font-size: 26rpx;
    color: #fff;
  }
}

// 表单
.form {
  background-color: #f4f4f4;

  &-content {
    margin: 20rpx 20rpx 0;
    padding: 0 20rpx;
    border-radius: 10rpx;
    background-color: #fff;
  }

  &-item {
    display: flex;
    height: 96rpx;
    line-height: 46rpx;
    padding: 25rpx 10rpx;
    background-color: #fff;
    font-size: 28rpx;
    border-bottom: 1rpx solid #ddd;

    &:last-child {
      border: none;
    }

    .label {
      width: 180rpx;
      color: #333;
    }

    .account {
      color: #666;
    }

    .input {
      flex: 1;
      display: block;
      height: 46rpx;
    }

    .radio {
      margin-right: 20rpx;
    }

    .picker {
      flex: 1;
    }
    .placeholder {
      color: #808080;
    }
  }

  &-button {
    height: 80rpx;
    text-align: center;
    line-height: 80rpx;
    margin: 30rpx 20rpx;
    color: #fff;
    border-radius: 80rpx;
    font-size: 30rpx;
    background-color: #27ba9b;
  }
}
</style>
